//
//  ZBAsyncLayerView.m
//  XZBProduct
//
//  Created by xzb on 2018/6/15.
//  Copyright © 2018年 xzb. All rights reserved.
//

#import "ZBAsyncLayerView.h"
#import <YYTextAsyncLayer.h>

@implementation ZBAsyncLayerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.contentsScale = [UIScreen mainScreen].scale;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

+(Class)layerClass {
    return [YYTextAsyncLayer class];
}

- (YYTextAsyncLayerDisplayTask *)newAsyncDisplayTask
{
    YYTextAsyncLayerDisplayTask *task = [YYTextAsyncLayerDisplayTask new];
    task.display = ^(CGContextRef context, CGSize size, BOOL(^isCancelled)(void)) {
        [self drawInContext:context backFrame:(CGRect){CGPointZero,size} isCanceled:isCancelled];
    };
    
    return task;
}

- (void)setAttributedText:(NSAttributedString *)attributedText {
    _attributedText = [attributedText copy];
    [self.layer setNeedsDisplay];
}


- (void)drawInContext:(CGContextRef)context backFrame:(CGRect)backFrame isCanceled:(BOOL (^)(void))isCancelled
{
    if (isCancelled && isCancelled()) return;
    
    if (self.backgroudColor) {
        CGContextSaveGState(context);
        [self.backgroudColor  setFill];
        UIRectFill(backFrame);
        CGContextRestoreGState(context);
    }
    
    [self.attributedText drawInRect:backFrame];
    
}
@end

